﻿using UnityEngine;
using System.Collections;

public class FlyCam : MonoBehaviour {

	private float _moveSpeed;
	private float _rotationSpeed;
	private Quaternion _orgQ;
	private float _mouseY;
	private float _mouseX;
	private Vector3 _homePos;
	void Start () {
		_moveSpeed = 5;
		_rotationSpeed = 5;
		_orgQ = this.transform.rotation;
	}

	void Update () {
		if(Input.GetKey(KeyCode.W)){
			this.transform.position += this.transform.forward*_moveSpeed*Time.deltaTime;
		}
		else if(Input.GetKey(KeyCode.S)){
			this.transform.position += -this.transform.forward*_moveSpeed*Time.deltaTime;
		}
		if(Input.GetKey(KeyCode.A)){
			this.transform.position += -this.transform.right*_moveSpeed*Time.deltaTime;
		}
		else if(Input.GetKey(KeyCode.D)){
			this.transform.position += this.transform.right*_moveSpeed*Time.deltaTime;
		}
		if(Input.GetMouseButton(1) && MouseOnScreen()){
			Screen.lockCursor = true;
			Screen.showCursor = false;
			_mouseY += Input.GetAxis("Mouse Y")*_rotationSpeed;
			_mouseX += Input.GetAxis("Mouse X")*_rotationSpeed;
			this.transform.rotation = Quaternion.Euler(-_mouseY+this.transform.rotation.x,_mouseX+this.transform.rotation.y,0);
		}
		else{
			Screen.lockCursor = false;
			Screen.showCursor = true;
			
		}
		if(Input.GetKeyDown(KeyCode.Home)){
			this.transform.position = _homePos;
		}
		if(Input.GetKeyDown(KeyCode.Insert)){
			_mouseX = 0;
			_mouseY = 0;
			this.transform.rotation = Quaternion.Euler(0,0,0);
		}
	}
	public bool MouseOnScreen(){
		float x = Input.mousePosition.x;
		if(x < 0){
			return false;
		}
		if(x > Screen.width){
			return false;
		}
		float y = (Screen.height) - Input.mousePosition.y;
		if(y < 0){
			return false;
		}
		if(y > Screen.height){
			return false;
		}
		return true;

	}


	public float MoveSpeed{
		get{return _moveSpeed;}
		set{value = _moveSpeed;}
	}
	public float RotationSpeed{
		get{return _rotationSpeed;}
		set{value = _rotationSpeed;}
	}
	public Vector3 HomePosition{
		get{return _homePos;}
		set{value = _homePos;}
	}
}
